package org.apache.ibatis.common.type;

import java.sql.*;

/**
 * @Name SqlXmlTypeHandler
 * @Description: [SQL Xml -> JAVA String] 类型处理器
 * @Version v1.0.0
 * @Author: lichao
 * @Date: 2024-05-10 18:15:31
 **/
public class SqlXmlTypeHandler extends BaseTypeHandler<String> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        SQLXML sqlxml = ps.getConnection().createSQLXML();
        try {
            sqlxml.setString(parameter);
            ps.setSQLXML(i, sqlxml);
        } finally {
            sqlxml.free();
        }
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return sqlXmlToString(rs.getSQLXML(columnName));
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return sqlXmlToString(rs.getSQLXML(columnIndex));
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return sqlXmlToString(cs.getSQLXML(columnIndex));
    }

    private String sqlXmlToString(SQLXML sqlxml) throws SQLException {
        if (sqlxml == null) return null;
        try {
            return sqlxml.getString();
        } finally {
            sqlxml.free();
        }
    }
}

